package com.itheima.tanhua.service;

import cn.hutool.core.collection.CollUtil;
import com.itheima.tanhua.api.CommentApi;
import com.itheima.tanhua.api.UserInfoApi;
import com.itheima.tanhua.domain.UserInfo;
import com.itheima.tanhua.enums.CommentType;
import com.itheima.tanhua.enums.LogType;
import com.itheima.tanhua.exception.BusinessException;
import com.itheima.tanhua.mongo.Comment;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhua.utils.UserHolder;
import com.itheima.tanhua.vo.CommentVo;
import com.itheima.tanhua.vo.ErrorResult;
import com.itheima.tanhua.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Lff
 * @date 2022/3/28
 */
@Service
@Slf4j
public class CommentService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    @Autowired
    private UserFreezeService userFreezeService;

    /**
     * 发布评论
     *
     * @param movementId 动态id
     * @param content    评论内容
     */
    public void publishComment(String movementId, String content) {
        //检查用户状态
        userFreezeService.checkUserStatus("2", UserHolder.getUser().getId());
        //封装comment对象
        Comment comment = new Comment();
        //设置Comment类型
        comment.setCommentType(CommentType.COMMENT.getType());
        //设置评论内容
        comment.setContent(content);
        //设置评论人
        comment.setUserId(UserHolder.getUser().getId());
        //设置评论事件
        comment.setCreated(System.currentTimeMillis());
        //设置被评论的动态id
        comment.setPublishId(new ObjectId(movementId));
        Integer commentCount = commentApi.save(comment);
        log.info("commentCount ===> {}", commentCount);
    }

    /**
     * 获取动态的所有评论
     *
     * @param movementId
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult getComments(String movementId, Integer page, Integer pagesize) {
        List<Comment> commentList = commentApi.findCommentAll(movementId, CommentType.COMMENT, page, pagesize);
        if (CollUtil.isEmpty(commentList)) {
            return new PageResult();
        }
        //整理出评论发布者的id
        List<Long> ids = CollUtil.getFieldValues(commentList, "userId", Long.class);
        //获取用户详情信息
        Map<Long, UserInfo> map = userInfoApi.getUserInfosToMap(ids, null);
        //填充模型
        List<CommentVo> results = commentList.stream().map(comment -> {
            CommentVo init = CommentVo.init(map.get(comment.getUserId()), comment);
            String key = Constants.COMMENTS_LIKE_KEY + comment.getId();
            String hashkey = Constants.COMMENTS_LIKE_HASHKEY + comment.getUserId();
            if (redisTemplate.opsForHash().hasKey(key, hashkey)) {
                //存在  已点赞
                init.setHasLiked(1);
            }
            return init;
        }).collect(Collectors.toList());
        //获取所有评论的数量
        Long count = commentApi.countCommentNum(movementId, CommentType.COMMENT);
        PageResult pr = new PageResult(page, pagesize, count, results);
        //返回数据
        return pr;
    }

    /**
     * 点赞
     *
     * @param movementId
     * @return
     */
    public Integer doLike(String movementId) {
        //获取当前用户的id
        Long id = UserHolder.getUser().getId();
        //调用api查询用户是否已点赞
        boolean flag = commentApi.hasComment(movementId, id, CommentType.LIKE);
        if (flag) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //构建动态id
        ObjectId publishId = movementId == null ? new ObjectId() : new ObjectId(movementId);

        //构建Comment
        Comment comment = new Comment();
        comment.setPublishId(publishId);
        //设置评论人id
        comment.setUserId(id);
        //设置为当前时间
        comment.setCreated(System.currentTimeMillis());
        comment.setCommentType(CommentType.LIKE.getType());
        //调用Api保存
        Integer save = commentApi.save(comment);
        //将结果存到reids中
        //构建key&hashKey
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + id;
        redisTemplate.opsForHash().put(key, hashKey, "1");
        //返回结果
        mqMessageService.sendLogMessage(UserHolder.getUser().getId(),
                LogType.LOG_TYPE_LIKE_MOVEMENT.getValue(), "movement", movementId);
        return save;
    }

    //取消点赞
    public Integer doDisLike(String movementId) {
        //获取当前用户的id
        Long id = UserHolder.getUser().getId();
        //调用api查询用户是否已点赞
        boolean flag = commentApi.hasComment(movementId, id, CommentType.LIKE);
        if (!flag) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //构建动态id
        ObjectId publishId = movementId == null ? new ObjectId() : new ObjectId(movementId);

        //构建Comment
        Comment comment = new Comment();
        comment.setPublishId(publishId);
        //设置评论人id
        comment.setUserId(id);
        comment.setCommentType(CommentType.LIKE.getType());
        //调用Api查询
        Integer delete = commentApi.delete(comment);
        //将结果存到reids中
        //构建key&hashKey
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + id;
        //删除缓存
        redisTemplate.opsForHash().delete(key, hashKey);
        //返回结果
        return delete;
    }

    /**
     * 喜欢
     *
     * @param movementId
     * @return
     */
    public Integer doLove(String movementId) {
        //获取当前用户的id
        Long id = UserHolder.getUser().getId();
        //调用api查询用户是否已点赞
        boolean flag = commentApi.hasComment(movementId, id, CommentType.LOVE);
        if (flag) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //构建动态id
        ObjectId publishId = movementId == null ? new ObjectId() : new ObjectId(movementId);

        //构建Comment
        Comment comment = new Comment();
        comment.setPublishId(publishId);
        //设置评论人id
        comment.setUserId(id);
        //设置为当前时间
        comment.setCreated(System.currentTimeMillis());
        comment.setCommentType(CommentType.LOVE.getType());
        //调用Api保存
        Integer save = commentApi.save(comment);
        //将结果存到reids中
        //构建key&hashKey
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + id;
        redisTemplate.opsForHash().put(key, hashKey, "1");
        //返回结果
        return save;
    }

    /**
     * 不喜欢
     *
     * @param movementId
     * @return
     */
    public Integer doUnLove(String movementId) {
        //获取当前用户的id
        Long id = UserHolder.getUser().getId();
        //调用api查询用户是否已点赞
        boolean flag = commentApi.hasComment(movementId, id, CommentType.LOVE);
        if (!flag) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //构建动态id
        ObjectId publishId = movementId == null ? new ObjectId() : new ObjectId(movementId);

        //构建Comment
        Comment comment = new Comment();
        comment.setPublishId(publishId);
        //设置评论人id
        comment.setUserId(id);
        comment.setCommentType(CommentType.LOVE.getType());
        //调用Api查询
        Integer delete = commentApi.delete(comment);
        //将结果存到reids中
        //构建key&hashKey
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + id;
        //删除缓存
        redisTemplate.opsForHash().delete(key, hashKey);
        //返回结果
        return delete;
    }

    /**
     * 点赞评论
     *
     * @param commentId
     * @return
     */
    public Integer doLikeComment(String commentId) {
        ObjectId commentId1 = commentId == null ? new ObjectId() : new ObjectId(commentId);
        //获取用户Id
        Long userId = UserHolder.getUser().getId();
        //判断是否点赞过该评论 //把点赞的评论id 作为publishId来查询
        boolean flag = commentApi.hasComment(commentId, userId, CommentType.MOVEMENT_COMMENT_LIKE);
        if (flag) {
            //评论已点赞
            throw new BusinessException(ErrorResult.likeCommentError());
        }
        //添加一条新的记录到comment表中
        Comment commentSave = new Comment();
        commentSave.setUserId(userId);
        commentSave.setPublishId(commentId1);
        commentSave.setCreated(System.currentTimeMillis());
        //将点赞记录保存到表中
        commentApi.saveComment(commentSave);
        //获取当前用户id
        Long id = UserHolder.getUser().getId();
        //填充一个Comment
        Comment comment = new Comment();
        //评论人id
        comment.setUserId(id);
        //评论id
        comment.setId(commentId1);
        Integer count = commentApi.updateCommentLikeCount(comment);
        //存到redis
        String key = Constants.COMMENTS_LIKE_KEY + commentId;
        String hashkey = Constants.COMMENTS_LIKE_HASHKEY + userId;
        redisTemplate.opsForHash().put(key, hashkey, "1");
        //返回数据
        return count;
    }

    public Integer doDisLikeComment(String commentId) {
        ObjectId commentId1 = commentId == null ? new ObjectId() : new ObjectId(commentId);
        //获取用户Id
        Long userId = UserHolder.getUser().getId();
        //判断是否点赞过该评论 //把点赞的评论id 作为publishId来查询
        boolean flag = commentApi.hasComment(commentId, userId, CommentType.MOVEMENT_COMMENT_LIKE);
        if (!flag) {
            //评论未点赞
            throw new BusinessException(ErrorResult.disLikeCommentError());
        }
        //从表中删除点赞记录
        Comment commentDel = new Comment();
        commentDel.setUserId(userId);
        commentDel.setPublishId(commentId1);
        //将点赞记录从表中删除
        commentApi.delComment(commentDel);
        //获取当前用户id
        Long id = UserHolder.getUser().getId();
        //填充一个Comment
        Comment comment = new Comment();
        //评论人id
        comment.setUserId(id);
        //评论id
        comment.setId(commentId1);
        Integer count = commentApi.updateCommentLikeCountRm(comment);
        //移除缓存
        String key = Constants.COMMENTS_LIKE_KEY + commentId;
        String hashkey = Constants.COMMENTS_LIKE_HASHKEY + userId;
        redisTemplate.opsForHash().delete(key, hashkey);
        //返回数据
        return count;
    }
}
